import {
    formatGMTDate
} from '../../../../assets/js/util.js'
import serversFilter from './serversFilter.vue'
import echarts from 'echarts'
export default {
    data() {
        return {
            xlsxTitle: '',
            /*当前页显示数量*/
            pageSize: 10,
            /*每页显示的数量*/
            pageSizes: [10, 20, 50, 100],
            /*dataTotal表数量*/
            dataTotal: 0,
            /*分页器*/
            currentPage: 1,
            loading: false,
            // 默认参数 和 URL
            SRC: '',
            DP: {
                p: '',
                f: ''
            },
            // title
            title: "分服概况",
            // 选择的时间
            date: '',
            /*表格数据*/
            tableData: [],
            /*表格数据全部*/
            tableDataAll: [],
            /*realTimeServiceContent 的宽*/
            realTimeServiceContent: '100%',
            /*表的宽度*/
            realTimeServiceTableWidth: "100%",
            /*数据表头*/
            tableHeader: [{
                prop: 'serverid',
                label: '服务器名称',
                width: '130px',
                fixed: true
            }, {
                prop: 'onlinenum',
                label: '在线人数',
                width: '120px',
                fixed: false
            }, {
                prop: 'pcu',
                label: 'PCU',
                width: '100px',
                fixed: false
            }, {
                prop: 'acu',
                label: 'ACU',
                width: '100px',
                fixed: false
            }, {
                prop: 'newUser',
                label: '新增用户',
                width: '120px',
                fixed: false
            }, {
                prop: 'distinctNewUser',
                label: '去重新增用户',
                width: '150px',
                fixed: false
            }, {
                prop: 'acitveUser',
                label: '活跃用户',
                width: '120px',
                fixed: false
            }, {
                prop: 'capacity',
                label: '服务器容量',
                width: '130px',
                fixed: false
            }, {
                prop: 'capacityUsedRadio',
                label: '实时使用率',
                width: '130px',
                fixed: false
            }, {
                prop: 'pcuYesterday',
                label: '昨日PCU',
                width: '120px',
                fixed: false
            }, {
                prop: 'cashUser',
                label: '付费账号数',
                width: '130px',
                fixed: false
            }, {
                prop: 'cash',
                label: '付费金额',
                width: '120px',
                fixed: false
            }, {
                prop: 'activeUserPayRadio',
                label: '活跃付费率',
                width: '130px',
                fixed: false
            }, {
                prop: 'the2Left',
                label: '昨日新增账号次留',
                width: '170px',
                fixed: false
            }, {
                prop: 'mac2Left',
                label: '昨日新增设备次留',
                width: '170px',
                fixed: false
            }, {
                prop: 'maxCapacityUsedRadioYesterday',
                label: '昨日最高使用率',
                width: '160px',
                fixed: false
            }],
            // 请求的参数
            postObj: {
                'date': '',
                'serverItmes': '0',
                'eventTagId': 'online'
            },
            // date=2017-6-2&serverItmes=6026,0&eventTagId=online
            onlinePostObj: {
                'date': '',
                'serverItmes': '0',
                'eventTagId': 'online'
            },
            // 当前全服最高负载
            lastMaxOnlineNumStr: '',
            // 服务器总数量
            serverNumStr: 0,
            // 全服实时在线
            real: {
                color: ['#3398DB'],
                tooltip: {
                    trigger: 'axis',
                    axisPointer: { // 坐标轴指示器，坐标轴触发有效
                        type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
                    }
                },
                dataZoom: [{
                    bottom: 0,
                    handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
                    handleSize: '80%',
                    handleStyle: {
                        color: '#fff',
                        shadowBlur: 3,
                        shadowColor: 'rgba(0, 0, 0, 0.6)',
                        shadowOffsetX: 2,
                        shadowOffsetY: 2
                    }
                }],
                grid: {
                    top: '10%',
                    left: '0%',
                    right: '1%',
                    bottom: '25%',
                    containLabel: true
                },
                toolbox: {
                    right: '20',
                    feature: {
                        dataZoom: {
                            yAxisIndex: 'none'
                        },
                        magicType: {
                            type: ['line', 'bar']
                        },
                        restore: {},
                        saveAsImage: {}
                    }
                },
                xAxis: [{
                    type: 'category',
                    data: [],
                    axisTick: {
                        alignWithLabel: true
                    },
                    axisLabel: {
                        interval: 0,
                        rotate: -90, //倾斜度 -90 至 90 默认为0
                        margin: 10,
                    },
                }],
                yAxis: [{
                    type: 'value'
                }],
                series: [{
                    name: '',
                    type: 'bar',
                    barWidth: '40%',
                    itemStyle: {
                        normal: {
                            color: new echarts.graphic.LinearGradient(
                                0, 0, 0, 1, [
                                    { offset: 0, color: '#83bff6' },
                                    { offset: 0.5, color: '#188df0' },
                                    { offset: 1, color: '#188df0' }
                                ]
                            )
                        },
                        emphasis: {
                            color: new echarts.graphic.LinearGradient(
                                0, 0, 0, 1, [
                                    { offset: 0, color: '#2378f7' },
                                    { offset: 0.7, color: '#2378f7' },
                                    { offset: 1, color: '#83bff6' }
                                ]
                            )
                        }
                    },
                    markLine: {
                        lineStyle: {
                            normal: {}
                        }
                    },
                    data: []
                }]
            },
            // 全服在线详细数据 表头
            tableHeader2: [{
                prop: 'itemName',
                label: '大区'
            }, {
                prop: 'serverid',
                label: '服务器ID'
            }, {
                prop: 'servername',
                label: '服务器名称'
            }, {
                prop: 'onlinenum',
                label: '在线人数'
            }],
            // 全服在线详细数据 表格数据
            tableData2: [],
            // 新增 在线 图表
            pay: {
                tooltip: {
                    trigger: 'axis'
                },
                legend: {
                    width: '90%',
                    height: '50%',
                    top: 430,
                    data: []
                },
                grid: {
                    top: '10%',
                    left: '0%',
                    right: '1%',
                    bottom: 150,
                    containLabel: true,
                },
                toolbox: {
                    right: '20',
                    feature: {
                        dataZoom: {
                            yAxisIndex: 'none'
                        },
                        magicType: {
                            type: ['line', 'bar']
                        },
                        restore: {},
                        saveAsImage: {}
                    }
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: [],
                    axisLabel: {
                        margin: 20,
                    },
                },
                yAxis: {
                    type: 'value',
                    // max: 10000
                },
                dataZoom: [{
                    bottom: 110,
                    handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
                    handleSize: '80%',
                    handleStyle: {
                        color: '#fff',
                        shadowBlur: 3,
                        shadowColor: 'rgba(0, 0, 0, 0.6)',
                        shadowOffsetX: 2,
                        shadowOffsetY: 2
                    }
                }],
                series: [{
                    name: '1',
                    type: 'line',
                    smooth: true,
                    data: [],
                }, {
                    name: '2',
                    type: 'line',
                    smooth: true,
                    data: [],
                }, {
                    name: '3',
                    type: 'line',
                    smooth: true,
                    data: [],
                }]
            },
            // 服务器数组
            servers: [],
            // 已选服务器标签
            dynamicTags: [],
            // 高级筛选模态框
            filterShow: false,
            // 服务器筛选开关
            serverSwitch: true,
            // 服务器的搜索框的值
            serverVal: '',
            // 服务器选择的数量
            serverNumber: 3,
            // 区服标签
            serverTagValue: '全区服',
            // 已经选择服务器的数量
            checkedServers: [],
            checkedServersCP: [],
            // 已选服务器标签
            dynamicTags: [],
            dynamicTagsCP: [],
            // 最下边loading 
            realLoadShow: true
        }
    },
    methods: {
        // 设置图表初始化宽度
        chartsWidth(el) {
            if (document.getElementById(el) !== null) {
                document.getElementById(el).style.width = window.innerWidth - 290 + "px";
            }
        },
        //初始化
        _init() {
            window.addEventListener('resize', function() {
                var resizeArr = ['realTimeDataChart', 'onlineChart']
                for (var j in resizeArr) {
                    this[resizeArr[j]].resize();
                }
            }.bind(this))
        },
        // 通用 成功 与 失败
        successFun(data) {
            this.$message({
                message: data,
                type: 'success'
            });
        },
        errorFun(data) {
            this.$message.error(data);
        },
        // 分页器
        // 控制每页的数量
        handleSizeChange(val) {
            this.pageSize = val;
            this.tableControl();
        },
        // 页数
        handleCurrentChange(val) {
            this.currentPage = val;
            this.tableControl();
        },
        tableControl() {
            this.tableData = this.tableDataAll.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize)
        },
        // 选择时间
        dateChange(val) {
            if (val === undefined) {
                this.errorFun('请选择查看时间！')
            } else {
                this.date = val;
                this.postObj.date = val;
            }
            if (this.tableData.length > 0) {
                this.getData(this.postObj);
            }
        },
        // 表格数据合并
        tableMergeData(data, data2) {
            this.dataTotal = 0;
            this.tableData = [];
            this.tableDataAll = [];
            data2['serverid'] = '总计';
            data.push(data2);
            for (var i = 0; i < data.length; i++) {
                data[i]["capacityUsedRadio"] = (data[i]["capacityUsedRadio"] * 100).toFixed(2) + "%";
                data[i]["activeUserPayRadio"] = (data[i]["activeUserPayRadio"] * 100).toFixed(2) + "%";
                data[i]["the2Left"] = data[i]["the2Left"] == 0 ? data[i]["the2Left"] = "" : (data[i]["the2Left"] * 100).toFixed(2) + "%";
                data[i]["mac2Left"] = data[i]["mac2Left"] == 0 ? data[i]["mac2Left"] = "" : (data[i]["mac2Left"] * 100).toFixed(2) + "%";
                data[i]["maxCapacityUsedRadioYesterday"] = data[i]["maxCapacityUsedRadioYesterday"] == 0 ? data[i]["maxCapacityUsedRadioYesterday"] = "" : (data[i]["maxCapacityUsedRadioYesterday"] * 100).toFixed(2) + "%";
            }
            this.tableDataAll = data;
            this.dataTotal = data.length;
            this.tableControl();
        },
        // 获取后台数据
        getData(data) {
            var that = this;
            var p = new Promise(function(resolve, reject) {
                that.loading = true;
                that.$http.jsonp(`${that.SRC}data/get.do?p=${that.DP.p}&f=${that.DP.f}&a=search`, {
                    params: { 'ps': `date=${data.date}&serverItmes=${data.serverItmes}&eventTagId=${data.eventTagId}` }
                }).then(function(res) {
                    resolve(res.body)
                })
            })
            p.then(function(value) {
                that.loading = false;
                var data = JSON.parse(value);
                data = JSON.parse(data.replace(/\"\{\"/g, '\{\"').replace(/\"\}\"/g, '\"\}'));
                if (parseInt(data["res"]) === 0) {
                    that.tableMergeData(data['serverRealTimeDetailDatas'], data['allSumServerRealTimeDetailData']);
                    that.echartsData(data);
                    that.lastMaxOnlineNumStr = data['lastMaxOnlineNumStr'];
                    that.serverNumStr = data['serverNumStr'];
                    that.tableData2 = data['detailDatas'];
                } else {
                    if (data['msg'] === undefined) {
                        that.errorFun('数据请求失败！')
                    } else {
                        that.errorFun(data['msg']);
                    }
                }
            })
        },
        // 改变表数据
        echartsData(d) {
            // 删除零的元素
            function removeZero(arr) {
                var date = new Date();
                if (arr.length > 25) {
                    for (var i = 0; i < arr.length; i++) {
                        if (arr[i] === 0 && i > date.getHours() * 11) {
                            arr[i] = '-'
                        }
                    }
                } else {
                    for (var i = 0; i < arr.length; i++) {
                        if (arr[i] === 0 && i > date.getHours()) {
                            arr[i] = '-'
                        }
                    }
                }
                return arr;
            }
            // 实时数据获取到数据渲染
            var data = d['chartData']['jsonStr'];
            this.realTimeDataChart.setOption({
                xAxis: {
                    data: data.columnkeys
                },
                series: [{
                    name: '在线人数',
                    data: data.data[0]
                }]
            });
            // 为下列新增，在线提供前三个人数最多的服
            if (this.onlinePostObj.serverItmes === '0') {
                this.onlinePostObj.serverItmes = '';
                this.checkedServers = [];
                this.checkedServersCP = [];
                this.dynamicTags = [];
                this.dynamicTagsCP = [];
                var serversName = data.columnkeys;
                serversName = serversName.splice(0, 3);
                for (var i = 0; i < this.servers.length; i++) {
                    for (var j = 0; j < serversName.length; j++) {
                        if (this.servers[i]['value'] === serversName[j]) {
                            this.checkedServers.push(this.servers[i]['label']);
                            this.dynamicTags.push(this.servers[i]['value'])
                            this.onlinePostObj.serverItmes += (this.servers[i]['label'] + ',');
                        }
                    }
                }
                this.checkedServersCP = this.checkedServers;
                this.dynamicTagsCP = this.dynamicTags;
                this.onlinePostObj.serverItmes = this.onlinePostObj.serverItmes.substring(0, this.onlinePostObj.serverItmes.length - 1);
                this.getOnlineData(this.onlinePostObj);
            }
        },
        echartsData2(d) {
            // 在线
            function judge(obj) {
                for (var i in obj) {　
                    return true;
                }
                return false;
            }
            var seriesData = [];
            if (!judge(d)) {
                var data = [];
                seriesData = [];
                data['names'] = [];
                data.columnkeys = [];
            } else {
                var data = d['serverRealTimeChart']['jsonStr'];
                for (var i = 0; i < data['names'].length; i++) {
                    var obj = {
                        name: data['names'][i],
                        data: data['data'][i],
                        type: 'line'
                    }
                    seriesData.push(obj);
                }
            }
            this.onlineChart.setOption({
                tooltip: {
                    trigger: 'axis'
                },
                legend: {
                    width: '90%',
                    height: '50%',
                    top: 430,
                    data: data['names']
                },
                grid: {
                    top: '10%',
                    left: '0%',
                    right: '1%',
                    bottom: 150,
                    containLabel: true,
                },
                toolbox: {
                    right: '20',
                    feature: {
                        dataZoom: {
                            yAxisIndex: 'none'
                        },
                        magicType: {
                            type: ['line', 'bar']
                        },
                        restore: {},
                        saveAsImage: {}
                    }
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: data.columnkeys,
                    axisLabel: {
                        margin: 20,
                    },
                },
                yAxis: {
                    type: 'value',
                    // max: 10000
                },
                dataZoom: [{
                    bottom: 110,
                    handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
                    handleSize: '80%',
                    handleStyle: {
                        color: '#fff',
                        shadowBlur: 3,
                        shadowColor: 'rgba(0, 0, 0, 0.6)',
                        shadowOffsetX: 2,
                        shadowOffsetY: 2
                    }
                }],
                series: seriesData
            }, true);
        },
        // 分服实时数据获取
        getOnlineData(data) {
            var that = this;
            var p = new Promise(function(resolve, reject) {
                that.$http.jsonp(`${that.SRC}data/get.do?p=${that.DP.p}&f=${that.DP.f}&a=updateServerData`, {
                    params: { 'ps': `date=${data.date}&serverItmes=${data.serverItmes}&eventTagId=${data.eventTagId}` }
                }).then(function(res) {
                    resolve(res.body)
                })
            })
            p.then(function(value) {
                var data = JSON.parse(value)
                data = JSON.parse(data.replace(/\"\{\"/g, '\{\"').replace(/\"\}\"/g, '\"\}'));
                that.realLoadShow = false;
                that.echartsData2(data);
            })
        },
        // 获取服务器list 平台list  服务器list
        getList() {
            var that = this;
            var pushData = function(pushArr, attr, data) {
                that[pushArr] = [];
                for (var i in data[attr]) {
                    if (data[attr][i] !== '0') {
                        that[pushArr].push({
                            value: i,
                            label: data[attr][i]
                        })
                    }
                }
            };
            this.$http.jsonp(`${this.SRC}data/get.do`, {
                params: {
                    p: this.DP.p,
                    f: this.DP.f,
                    a: "initParam",
                    ps: ""
                }
            }).then(function(res) {
                var data = JSON.parse(JSON.parse(res.body));
                if (parseInt(data["res"]) === 0) {
                    // 后台select的数据
                    var lists = ["serverItmes"];
                    // 页面select名字
                    var nameLists = ["servers"];
                    for (var i = 0; i < lists.length; i++) {
                        if (data[lists[i]] !== undefined) {
                            pushData(nameLists[i], lists[i], data);
                        }
                    }
                } else {
                    this.getErrorMsg(Number(data.res))
                }
            })
        },
        // chooseServers选择服务器
        chooseServers() {
            this.filterShow = true;
        },
        // setOnline 选择在线或新增
        setOnline(str) {
            this.realLoadShow = true;
            this.onlinePostObj.eventTagId = str;
            this.getOnlineData(this.onlinePostObj);
        },
        // 全选
        allSelect() {
            this.checkedServers = [];
            this.dynamicTags = [];
            for (var y = 0; y < this.servers.length; y++) {
                this.checkedServers.push(this.servers[y]['label']);
                this.dynamicTags.push(this.servers[y]['value'])
            }
            this.serverNumber = this.checkedServers.length;
        },
        // 不选
        noSelect() {
            this.checkedServers = [];
            this.dynamicTags = [];
            this.serverNumber = this.checkedServers.length;
        },
        // 反选
        invertSelect() {
            var servers = [];
            var tags = [];
            for (var y = 0; y < this.servers.length; y++) {
                servers.push(this.servers[y]['label']);
                tags.push(this.servers[y]['value'])
            }
            for (var i = 0; i < servers.length; i++) {
                for (var j = 0; j < this.checkedServers.length; j++) {
                    if (this.checkedServers[j] === servers[i]) {
                        servers.splice(i, 1);
                        tags.splice(i, 1);
                    }
                }
            }
            this.checkedServers = servers;
            this.dynamicTags = tags;
            this.serverNumber = this.checkedServers.length;
        },
        // 服务选择
        handleCheckedServersChange(val) {
            this.serverNumber = val.length;
            this.dynamicTags = [];
            for (var i = 0; i < this.servers.length; i++) {
                for (var j = 0; j < val.length; j++) {
                    if (val[j] === this.servers[i]['label']) {
                        this.dynamicTags.push(this.servers[i]['value'])
                    }
                }
            }
        },
        // 区服标签点击
        handleClose(tag) {
            this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
            for (var i = 0; i < this.servers.length; i++) {
                if (tag === this.servers[i]['value']) {
                    for (var j = 0; j < this.checkedServers.length; j++) {
                        if (this.checkedServers[j] === this.servers[i]['label']) {
                            this.checkedServers.splice(j, 1)
                        }
                    }
                }
            }
        },
        // 模态框确定
        sure() {
            this.filterShow = false;
            this.checkedServersCP = this.checkedServers;
            this.dynamicTagsCP = this.dynamicTags;
            this.onlinePostObj.serverItmes = this.checkedServers.join(',');
            this.getOnlineData(this.onlinePostObj);
        },
        // 模态框取消关闭数据不记录
        cancel() {
            this.filterShow = false;
            this.checkedServers = this.checkedServersCP;
            this.dynamicTags = this.dynamicTagsCP;
        },
        // 每隔15秒一次
        setTimeOnline() {
            var that = this;
            setInterval(function() {
                if (that.$route.path === '/main/realTime/realTimeService') {
                    console.log(2)
                    that.getData(that.postObj);
                    that.getOnlineData(that.onlinePostObj);
                }
            }, 15000)
        },
        // 表格下载
        excel(tableIndex, sheet) {
            var that = this;
            that.xlsxTitle = sheet + "-" + that.postObj.date;
            if (tableIndex === '') {
                that.downloadExl(that.tableHeader, that.tableDataAll, that.xlsxTitle, sheet);
            } else if (tableIndex === 2) {
                that.downloadExl(that['tableHeader' + tableIndex], that['tableData' + tableIndex], that.xlsxTitle, sheet);
            }
        }
    },
    components: {
        'v-servers': serversFilter,
    },
    computed: {
        // 区服过滤
        newServers: function() {
            var that = this;
            return that.servers.filter(function(item) {
                return item.value.toLowerCase().indexOf(that.serverVal.toLowerCase()) !== -1;
            })
        },
    },
    mounted() {
        // 初始化URL
        this.SRC = this.$store.getters.src;
        this.DP.p = localStorage.getItem('ZULONGBIPROJECTID');
        this.DP.f = localStorage.getItem('ZULONGBIPAGEID');
        // 初始化时间
        this.date = new Date();
        this.postObj.date = formatGMTDate(new Date(), true);
        this.onlinePostObj.date = formatGMTDate(new Date(), true);
        // 获取到服务器list
        this.getList();

        this.getData(this.postObj)
            // 实时数据
        this.realTimeDataChart = echarts.init(document.getElementById('realTimeData'));
        this.realTimeDataChart.setOption(this.real);
        this.onlineChart = echarts.init(document.getElementById('online'));
        this.onlineChart.setOption(this.pay);
        this._init();

        setTimeout(this.setTimeOnline, 15000);
    }
}